package com.landeb.shop.huo.act;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.adapter.ActSearchGVAdapter;
import com.landeb.shop.huo.adapter.ActSearchSimpleAdapter;
import com.landeb.shop.huo.bean.ItemActSearchFlow;
import com.landeb.shop.huo.httpRequest.SearchActRequest;
import com.landeb.shop.huo.view.FixedGridView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SearchActivity extends BaseActivity implements View.OnClickListener {


    private Button btnSearch, btnDelete;
    private LinearLayout btnBack;
    private EditText editSearch;
    private FixedGridView mRecentGV, mHotGV;

    private List<ItemActSearchFlow.DataBean> mHotList;
    private List<String> mRecentList;

    private ActSearchGVAdapter mHotAdapter;
    private ActSearchSimpleAdapter mRecentAdapter;

    private String mUrl;
    private Retrofit mRetrofit;
    private SearchActRequest mRequest;

    private String searchWord = "";

    public static void toAct(Context context) {
        Intent intent = new Intent(context, SearchActivity.class);
        context.startActivity(intent);
    }

    public static void toAct(Context context, String searchWord) {
        Intent intent = new Intent(context, SearchActivity.class);

        intent.putExtra("searchWord", searchWord);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        OkHttpClient client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(SearchActRequest.class);

        Intent intent = getIntent();

        if (!TextUtils.isEmpty(intent.getStringExtra("searchWord"))) {
            searchWord = intent.getStringExtra("searchWord");
        }

        initView();
        initData();
        initEvent();

        refresh();
    }

    private void initEvent() {

        btnBack.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
        btnDelete.setOnClickListener(this);

        mRecentAdapter = new ActSearchSimpleAdapter(this, mRecentList);
        mRecentGV.setAdapter(mRecentAdapter);

        mHotAdapter = new ActSearchGVAdapter(this, mHotList);
        mHotGV.setAdapter(mHotAdapter);

        mRecentGV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // TODO: 2016/11/16  最近搜索跳转

                SearchResultActivity.toAct(SearchActivity.this, SearchResultActivity.FLAG_KEYWORD, mRecentList.get(i));

            }
        });

        mHotGV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // TODO: 2016/11/16 热门推荐使用keyword跳转
//                获取跳转keyword
                String keyword = mHotList.get(i).getKeyword();
                //添加进搜索历史
                addSearchHistory(mHotList.get(i).getName());

                SearchResultActivity.toAct(SearchActivity.this, SearchResultActivity.FLAG_KEYWORD, keyword);

//                Toast.makeText(SearchActivity.this, keyword, Toast.LENGTH_SHORT).show();

            }
        });
    }

    private void initData() {

        mRecentList = new ArrayList<>();
        mRecentList.addAll(getRecentSearchData());
//        mRecentList.add(new ItemActSearchFlow.DataBean("玉米", "1"));
//        mRecentList.add(new ItemActSearchFlow.DataBean("黄瓜", "2"));
        mHotList = new ArrayList<>();
//        mHotList.add(new ItemActSearchFlow("会员提前抢", "1"));
//        mHotList.add(new ItemActSearchFlow("小米5", "3"));
//        mHotList.add(new ItemActSearchFlow("海尔空调", "1"));
//        mHotList.add(new ItemActSearchFlow("led电视", "1"));
//        mHotList.add(new ItemActSearchFlow("宝洁五折起", "1"));
//        mHotList.add(new ItemActSearchFlow("冰箱抢先订", "1"));
//        mHotList.add(new ItemActSearchFlow("奶粉买三免一", "1"));

    }

    private void initView() {
        btnBack = (LinearLayout) findViewById(R.id.act_search_btn_back);
        btnSearch = (Button) findViewById(R.id.act_search_btn_search);
        btnDelete = (Button) findViewById(R.id.act_search_btn_delete);

        editSearch = (EditText) findViewById(R.id.act_search_edit_search);

        mRecentGV = (FixedGridView) findViewById(R.id.act_search_flowLayout_recent);
        mHotGV = (FixedGridView) findViewById(R.id.act_search_flowLayout_hot);

        editSearch.setText(searchWord);
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.act_search_btn_back:
                // TODO: 2016/10/22 返回键
                onBackPressed();
                break;

            case R.id.act_search_btn_search:
                // TODO: 2016/10/22 搜索逻辑

                String searchCode = editSearch.getText().toString();
                // 添加进搜索历史
                addSearchHistory(searchCode);

//                Toast.makeText(SearchActivity.this, searchCode, Toast.LENGTH_SHORT).show();
                SearchResultActivity.toAct(this, SearchResultActivity.FLAG_KEYWORD, searchCode);

                break;

            case R.id.act_search_btn_delete:
                // TODO: 2016/11/16 删除本地搜索记录
                mRecentList.clear();
                mRecentAdapter.notifyDataSetChanged();
                break;

        }

    }

    /**
     * 添加最近搜索的方法 保持搜索项目在十五个以下
     */
    private void addSearchHistory(String item) {

        if (item.isEmpty()) {
            return;
        }

        if (mRecentList == null) {
            return;
        }

        if (mRecentList.contains(item)) {
            return;
        }

        if (mRecentList.size() == 9) {
            mRecentList.remove(9 - 1);
            mRecentList.add(0, item);
            return;
        }
        mRecentList.add(0, item);
    }

    private void refresh() {

        mRequest.getHotSearch()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ItemActSearchFlow>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ItemActSearchFlow itemActSearchFlow) {

                        mHotList.clear();
                        mHotList.addAll(itemActSearchFlow.getData());
                        mHotAdapter.notifyDataSetChanged();


                    }
                });


    }

    //    搜索历史持久化存储方法
    private void setRecentSearchData(List<String> mRecentList) {


        SharedPreferences preferences = getSharedPreferences("searchData", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        Gson gson = new Gson();
        String searchData = gson.toJson(mRecentList);

        editor.putString("searchData", searchData);
        editor.commit();

    }

    //读取搜索历史的方法
    private List<String> getRecentSearchData() {

        List<String> dataList = new ArrayList<>();

        SharedPreferences preferences = getSharedPreferences("searchData", Context.MODE_PRIVATE);
        Gson gson = new Gson();

        String searchData = preferences.getString("searchData", null);
        if (searchData == null) {
            return dataList;
        }

        dataList = gson.fromJson(searchData, new TypeToken<List<String>>() {
        }.getType());
        return dataList;
    }

    @Override
    protected void onResume() {
        super.onResume();

        mRecentList.clear();
        mRecentList.addAll(getRecentSearchData());
        mRecentAdapter.notifyDataSetChanged();


    }

    @Override
    protected void onPause() {
        super.onPause();

        setRecentSearchData(mRecentList);
    }
}
